package com.itserver.utils.exception;

import lombok.extern.slf4j.Slf4j;
import com.itserver.pojo.Result;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.resource.NoResourceFoundException;


@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {
    @ExceptionHandler
    public Result handleException(Exception e){
        log.error("系统异常 {}",e.getMessage());
        return Result.error(e.getMessage());
    }

    @ExceptionHandler
    // 404 找不到资源
    public Result handleException(NoResourceFoundException e){
        log.error("404 找不到资源 {}",e.getMessage());
        return Result.error(e.getMessage(),404);
    }

    @ExceptionHandler
    public Result RunHandleException(RuntimeException e){
        log.error("运行时异常 {}",e.getMessage());
        return Result.error(e.getMessage());
    }
    @ExceptionHandler
    public Result DupHandleException(DuplicateKeyException e){
        log.error("主键冲突：{}",e.getMessage());
        String message = e.getMessage();
        int i = message.lastIndexOf("Duplicate entry");
        String errMsg = message.substring(i);
        String[] arr = errMsg.split(" ");
        return Result.error(arr[2] + "已存在");
    }
    @ExceptionHandler
    public Result handleDataIntegrityViolation(DataIntegrityViolationException e){
        log.error("缺少必填项： {}",e.getMessage());
        String message = e.getMessage();
        int i = message.lastIndexOf("Column");
        String errMsg = message.substring(i);
        String[] arr = errMsg.split(" ");
        return Result.error(arr[1] + "不能为空");
    }
    @ExceptionHandler
    public Result handleNullPointException(NullPointerException e) {
        log.error("空指针异常：{}",e.getMessage());
        return Result.error("空指针异常");
    }
    @ExceptionHandler
    //401 异常
    public Result handleAuthException(AuthenticationException e){
        log.error("认证失败 {}",e.getMessage());
        return Result.error(e.getMessage(),401);
    }

    @ExceptionHandler
    public Result handleException(CustomException e){
        log.error("自定义异常 {}",e.getMessage());
        return Result.error(e.getMessage());
    }
}
